<template>
  <el-container>
    <el-header>
      <div class="headerWrap">
        <div class="headerWrapItem">
          <span class="titleName">
            上传数据列表
          </span>
          <el-switch
            v-model="isServerTest"
            :active-text="'服务器测试'"
            :inactive-text="'本地测试'"
            style="float:right; margin-top: 10px"
          />
        </div>
        <div>
          <el-button
            size="small"
            type="primary"
            @click="startPrediction"
            style="float:right;margin-left: 10px"
            ><i class="el-icon-upload el-icon--right icon-item"></i>开始测试
          </el-button>
          <el-popconfirm title="确定删除该任务吗？" @confirm="deleteRows">
            <el-button
              size="small"
              type="danger"
              style="float:right; margin-left: 10px"
              slot="reference"
              ><i class="el-icon-delete icon-item"></i>批量删除
            </el-button>
          </el-popconfirm>

          <el-upload
            class="upload-demo"
            action="string"
            :show-file-list="false"
            accept=".py"
          >
            <el-button plain size="small" type="primary"
              ><i class="el-icon-upload icon-item"></i>加载后处理文件</el-button
            >
          </el-upload>


          <el-button v-if="!isGlobalUploaded"     @click="isGlobalUploaded = true" size="small">
    后处理文件全局上传
  </el-button>

          <el-button v-else @click="isGlobalUploaded = false"  size="small">取消</el-button>

          <el-upload
            class="upload-demo"
            action="string"
            :http-request="uploadFiles"
            multiple
            :show-file-list="false"
            accept=".nii,.nii.gz,.dcm,.raw,.mhd"
          >
            <el-button plain size="small" type="primary"
              ><i class="el-icon-upload icon-item"></i>上传文件</el-button
            >
          </el-upload>
        </div>
      </div>
    </el-header>
    <el-main>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :row-key="getRowKey"
        border
        style="width:100%; height: 100%"
        @selection-change="handleSelectionChange"
        :header-cell-style="{
          color: 'black',
          fontSize: '20px',
          backgroundColor: '#fafafa'
        }"
      >
        <el-table-column
          type="selection"
          width="60"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column
          align="center"
          header-align="center"
          prop="id"
          label="任务ID"
          width="200"
        >
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="file"
          label="文件名称"
          width="450"
        >
        </el-table-column>
        <el-table-column
          prop="model"
          label="模型"
          width="417"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <el-select
              v-model="selectedModels[scope.$index]"
              :placeholder="isRowSelected[scope.$index] ? '' : '请选择'"
              value-key="value"
              clearable
              filterable
              @change="handleModelChange(scope.$index, $event)"
              class="center"
            >
              <el-option
                v-for="item in options"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="后处理文件" width="150">
          <template slot-scope="scope">
            <el-upload
            class="upload-demo"
            action="string"
            :show-file-list="false"
            accept=".py"
          >
            <el-button plain size="small" @click="isGlobalUploaded = true"
              >后处理文件</el-button
            >
          </el-upload>

          </template>
        </el-table-column>

        <el-table-column
          align="center"
          header-align="center"
          prop="state"
          label="状态"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.state">
              {{ getTagName(scope.row.state) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="do"
          label="操作"
          width="180"
        >
<!--          <el-link type="primary">3D数据查看</el-link>-->
          <el-link type="primary" @click="deleteRows">删除</el-link>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
</template>

<script>
import axios from "axios";
import moment from "moment";

// 生成日期和时间的 ID
const generateId = () => {
  const date = moment().format("YYYYMMDD"); // 当前日期（年月日）
  const time = moment().format("HHmmss"); // 当前时间（时分秒）
  const random = Math.floor(Math.random() * 100); // 生成 0 到 99 之间的随机数

  return `${date}${time}${random}`;
};

const tagStatusMap = {
  success: "成功",
  warning: "上传中",
  danger: "异常",
  info: "待上传",
  primary: "预测中"
};

export default {
  name: "ShowDataList",
  data() {
    return {
      tableData: [
        // {
        //   id: "202306241955208",
        //   file: "0b2be9e0-886b-4144-99f0-8bb4c6eaa840.nii.gz",
        //   fileObject: {},
        //   state: "info"
        // },
        // {
        //   id: "02",
        //   file: "0b2be9e0-886b-4144-99f0-8bb4c6eaa81.nii.gz",
        //   fileObject: {},
        //   state: "info"
        // },
        // {
        //   id: "03",
        //   file: "0b2be9e0-886b-4144-99f0-8bb4c6eaa842.nii.gz",
        //   fileObject: {},
        //   state: "info"
        // }
      ],
      options: [
        {
          value: "nnunet",
          label: "nnUNet_Model"
        },
        {
          value: "nnformer",
          label: "nnFormer_Model"
        },
        {
          value: "GE-UNET",
          label: "GE-UNET-Model"
        }
      ],
      value: "",
      selectedIds: [], // 选中的ID列表
      selectedModels: {}, // 选中的模型名称,使用对象以行索引为键
      isRowSelected: {}, // 记录每一行是否被选中
      isServerTest: false, // 默认为本地测试

      imagePath: "", // 图像路径
      tagStatus: tagStatusMap,
      isGlobalUploaded: false // 判断是否全局上传后处理文件
    };
  },

  computed: {
    getTagName() {
      return function(state) {
        return this.tagStatus[state];
      };
    }
  },
  methods: {
    // initializeTableData() {
    //   this.tableData = this.tableData.map(item => {
    //     return {
    //       ...item,
    //       state: "待上传"
    //     };
    //   });
    // },
    handleGlobalUpload() {
      // Update the isGlobalUploaded state to true
      this.isGlobalUploaded = true;

      // Show a success message
      this.$message.success("文件上传成功");
    },
    renderHeader(h, { column }) {
      return h("div", [
        h("span", column.label),
        h(
          "el-tooltip",
          {
            props: {
              effect: "dark",
              content:
                "支持三种模型的加载\n，nnUNet，以及使用CNN和Transformer架构且精度更高的nnFormer，以及自己改进的GE-UNET",
              placement: "top",
              popperClass: "popperClassStyle"
            }
          },
          [
            h("i", {
              class: "el-icon-question",
              style: "color:#409eff;margin-left:5px;"
            })
          ]
        )
      ]);
    },

    handleSelectionChange(selection) {
      this.selectedIds = selection.map(row => row.file);
      this.tableData.forEach((row, rowIndex) => {
        const isSelected = selection.find(item => item.file === row.file);
        this.isRowSelected[rowIndex] = isSelected;
        if (isSelected) {
          if (!this.selectedModels[rowIndex]) {
            // 如果选中状态为true且selectedModels[rowIndex]不存在值，设置为第一个选项
            this.$set(this.selectedModels, rowIndex, this.options[0].value);
            // this.selectedModels[rowIndex] = this.options[0].value
          }
        } else {
          this.selectedModels[rowIndex] = "";
        }
      });
    },
    handleModelChange(rowIndex, selectedModel) {
      if (this.selectedModels[rowIndex]) {
        const file = this.tableData[rowIndex].file;
        if (!this.selectedIds.includes(file)) {
          this.selectedIds.push(file);
          this.$refs.multipleTable.toggleRowSelection(this.tableData[rowIndex]);
        }
        this.selectedModels[rowIndex] = selectedModel;
      }
    },
    deleteRows() {
      // Delete selected rows
      if (this.selectedIds.length > 0) {
        this.tableData = this.tableData.filter(
          row => !this.selectedIds.includes(row.file)
        );
        this.selectedIds = [];
        this.selectedModels = {};
        this.isRowSelected = {};
        this.$refs.multipleTable.clearSelection();
        this.$message.success("文件删除成功");
      } else {
        this.$message.warning("未选中删除行！");
      }
    },

    updateRowState(file, state) {
      const rowIndex = this.tableData.findIndex(row => row.file === file);
      if (rowIndex !== -1) {
        this.$set(this.tableData[rowIndex], "state", state);
      }
    },

    getRowKey(row) {
      return row.file; // Use the 'file' property as the unique identifier
    },
    startPrediction() {
      // 处理开始测试按钮点击事件
      if (this.selectedIds.length > 0) {
        if (this.isServerTest) {
          this.processTasksParallel();
        } else {
          this.processTasks(0);
        }
      }
    },

    // 本地测试
    processTasks(index) {
      if (index >= this.selectedIds.length) {
        // 所有任务处理完成
        return;
      }

      const fileName = this.selectedIds[index];
      const rowIndex = this.tableData.findIndex(row => row.file === fileName);
      const fileObject = this.tableData.find(row => row.file === fileName).fileObject;
      const fileId = this.tableData.find(row => row.file === fileName).id;

      if (rowIndex !== -1) {
        this.updateRowState(fileName, "warning");
        // Get the selected file and create a FormData object
        // const filepath = this.tableData[rowIndex].filepath;
        const formData = new FormData();
        formData.append("fileobj", fileObject);
        // formData.append("fileid",fileId);

        // Upload the file to the backend
        axios
          .post("/upload", formData)
          .then(response => {
            // 根据返回的数据判断状态并更新

            if (response.data.fileStatus === "success") {
              this.updateRowState(fileName, "primary");
            } else {
              this.updateRowState(fileName, "danger");
            }

            // using axios:
            // const { file: selectedFile, filepath} = this.tableData[rowIndex]; // 修改变量名
            const params = {
              fileId: fileId,
              model: this.selectedModels[rowIndex],
              filepath: response.data.filepath
            };
            axios.get("/predict", { params }).then(response => {
              // console.log(response);
              const result = response.data;

              if (result.predictState === "success") {
                this.updateRowState(fileName, "success");
              } else {
                this.updateRowState(fileName, "danger");
              }

              // 处理下一个任务
              this.processTasks(index + 1);
            });
          })
          .catch(error => {
            this.updateRowState(fileName, "danger");

            // 处理下一个任务
            this.processTasks(index + 1);
          });
      }
    },

    handleGlobalPostProcessingUpload() {
    // Show a file upload dialog and handle the file upload
    // After successful upload, display a success message
    // For demonstration purposes, let's assume the upload was successful
    this.isGlobalUploaded = true;
    this.$message.success("后处理文件上传成功");
  },

    // 服务器测试
    processTasksParallel() {
      this.selectedIds.forEach(fileName => {
        const rowIndex = this.tableData.findIndex(row => row.file === fileName);
        if (rowIndex !== -1) {
          this.updateRowState(fileName, "warning");

          const fileId = this.tableData.find(row => row.file === fileName).id;
          const fileObject = this.tableData[rowIndex].fileObject;
          const formData = new FormData();
          formData.append("fileobj", fileObject);

          axios
            .post("/upload_fuwuqi", formData)
            .then(response => {
              // 根据返回的数据判断状态并更新
              if (response.data.fileStatus === "success") {
                this.updateRowState(fileName, "primary");

                // 文件上传成功后，请求预测
                const params = {
                  fileId: fileId, // Replace fileId with the correct fileId for your request
                  model: this.selectedModels[rowIndex], // Replace with the correct model
                  filepath: response.data.filepath // Replace with the correct filepath
                };

                console.log(params);

                axios
                  .get("/predict_fuwuqi", { params })
                  .then(response => {
                    const result = response.data;
                    console.log(result);

                    if (result.predictState === "success") {
                      this.updateRowState(fileName, "success");
                    } else {
                      this.updateRowState(fileName, "danger");
                    }
                  })
                  .catch(error => {
                    this.updateRowState(fileName, "danger");
                  });
              } else {
                this.updateRowState(fileName, "danger");
              }
            })
            .catch(error => {
              this.updateRowState(fileName, "danger");
            });
        }
      });
    },

    // 上传图像方法
    uploadFiles(param) {
      console.log(param);
      if (this.tableData.find(item => item.file === param.file.name)) {
        this.$message.warning("该文件已上传，请不要重复上传");
      } else {
        this.tableData.unshift({
          file: param.file.name,
          // id: uuid().substr(0, 8),
          id: generateId(),
          fileObject: param.file,
          state: "info"
        });
      }
    },
    // 选择的文件超出限制的文件总数量时触发
    limitCheck() {
      this.$message.warning("每次只能上传三个文件！");
    }
  }
};
</script>

<style scoped lang="less">
.titleName {
  color: black;
  font-size: 30px;
  vertical-align: middle;
  font-weight: bold;
  margin-right: 10px;
}

.upload-demo {
  display: inline-flex;
  align-items: center;
}
.upload-post {
  display: inline-flex;
  align-items: center;
}

.center {
  text-align: center;
}

.select-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.headerWrap {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .headerWrapItem {
    display: flex;
    justify-content: flex-start;
  }
}

.icon-item {
  margin-right: 5px;
}
.tagStatus {
  border: none;
  background: none;
  font-size: 14px;
}
.red {
  color: red;
}
</style>
